<?php
/**
 * Created by PhpStorm.
 * User: lzh 9157374
 * Date: 2018/7/1
 * Time: 下午5:40
 */
namespace app\controller;
use Core\common\Wechat;
class index extends _base
{
    public function __construct()
    {
        parent::__construct();
    }


//$user_id = $this->getUserId(I('token'));  用户token
//  首页数据
    public function index() {
        //图片轮播
        $Params['where']['box_top'] = 1;
        $Params['field'] = ['id','box_img'];
        $homeDatas = M('box_series')->lists($Params);
        $homeData = array();
        foreach ($homeDatas as $v) {
            $imgAll = array(
                'allImg'=>tomedia($v['box_img']),
                'id'=>$v['id'],
            );
            array_push($homeData,$imgAll);
        }
        //首页盲盒分类
        $ParamsType['where']['status'] = 1;
        $ParamsType['field'] = ['id','boxname'];
        $boxType = M('box_type')->top($ParamsType);

        $this->create_json_info('success', '成功', compact('homeData','boxType'));
    }

//首页搜索
    public function indexSearch(){
        $boxname = I('boxname');
        $aParams['where']['box_name LIKE'] = "%{$boxname}%";
        $aParams['field'] = ['*'];
        $boxList = M('box_series')->lists($aParams);
        foreach ($boxList as $k=>$v) {
            $boxList[$k]['box_img'] = tomedia($v['box_img']);
            $boxList[$k]['box_image'] = tomedia($v['box_image']);
        }

        $this->create_json_info('success', '成功', compact('boxList'));
    }

//  首页盲盒分类列表
    public function typeList(){
        $ParamsCount['where']['type_id'] = I('typeId');
        $page = I('page')?I('page'):1;
        $total= M('box_series')->count($ParamsCount);

        $aParams['where']['type_id'] = I('typeId');
        $aParams['limit'] = [($page-1)*6,6];
        $aParams['field'] = ['*'];
        $typeList = M('box_series')->lists($aParams);
        foreach ($typeList as $k=>$v) {
            $typeList[$k]['box_img'] = tomedia($v['box_img']);
            $typeList[$k]['box_image'] = tomedia($v['box_image']);
        }

        $this->create_json_info('success', '成功', compact('typeList','total','page'));
    }

//  获取盲盒系列数据-一条
    public function getSeries(){
        $typeid = I('id');

        //盲盒系列信息
        $Params['where']['id'] = $typeid;
        $seriesDetail = M('box_series')->getData($Params);
        $seriesDetail['box_img'] = tomedia($seriesDetail['box_img']);
        $seriesDetail['box_image'] = tomedia($seriesDetail['box_image']);//盲盒盒子已购图
        $seriesDetail['box_image_unsold'] = tomedia($seriesDetail['box_image_unsold']);//盲盒盒子未购图

        //收集信息
        $user_id = $this->getUserId(I('token'));
        $ParamCollect['where']['typeId'] = $seriesDetail['id'];
        $ParamCollect['where']['user_id'] = $user_id;
        $ParamCollect['field'] = ['boxId'];
        $list = M('user_collect')->lists($ParamCollect);
        $result = array_unique($list,SORT_REGULAR);  //用户购买的盒子id

        $seriesDetail['result'] = $result; //用户收集的数据

        $ParamList['field'] = ['id','boxlist_name','img_sold','img_unsold'];
        $ParamList['where']['boxtype_id'] = $seriesDetail['id'];
        $boxList = M('box_list')->lists($ParamList); //所有的系列盒子
        if($boxList){
            foreach($boxList as  $key => $item){
                $arr[$boxList[$key]['id']] = $item;
//                $arr[$boxList[$key]['typeId']] = $seriesDetail['id'];
            }
            if($result){
                foreach($result as $value){
                    foreach($arr as $arrkey => $arrItem){
                        if($value['boxId'] == $arrkey){
                            $arr[$arrkey]['image'] = tomedia($arrItem['img_sold']);
                        }else{
                            if(!$arr[$arrkey]['image']){
                                $arr[$arrkey]['image'] = tomedia($arrItem['img_unsold']);
                            }
                        }
                    }
                }
            }else{
                foreach($arr as $arrkey => $arrItem){
                    $arr[$arrkey]['image'] = tomedia($arrItem['img_unsold']);
                }
            }
        }


        $seriesDetail['boxList'] = $arr; //用户收集的数据
        //盲盒渲染是否可选列表
        $totalSum = pdo_fetchcolumn("SELECT sum(box_num) FROM " . tablename('sjtc_manghe_box_list') . "  WHERE boxtype_id = $typeid ");//入库总数
        $totalSale = pdo_fetchcolumn("SELECT sum(sale_num) FROM " . tablename('sjtc_manghe_box_list') . "  WHERE  boxtype_id = $typeid ");//已售
        $orderSum = pdo_fetchcolumn("SELECT sum(order_buySum) FROM " . tablename('sjtc_manghe_order') . "  WHERE boxTypeId = $typeid And status < 3");//已下单未发货的数量
        //$totalSum-$totalSale  //实际库存
        $stock = $totalSum-$totalSale-$orderSum; //当前可操作库存

        if($stock>8){
            $optional = rand(1,8);//可选盲盒数
            $optionalNo = 9 - $optional;//不可选盲盒数
        }else{
            $optional = $stock;//可选盲盒数
            $optionalNo = 9 - $stock;//不可选盲盒数
        }

        $arrayChoose = array();
        for ($i = 1; $i<=$optional; $i++) {
            $arrayChoose[$i]['chooseBox'] = 1 ;
            $arrayChoose[$i]['box_img'] = $seriesDetail['box_image_unsold'];
        }
        $arrayNoChoose = array();
        for ($i = 1; $i<=$optionalNo; $i++) {
            $arrayNoChoose[$i]['chooseBox'] = 2;
            $arrayNoChoose[$i]['box_img'] = $seriesDetail['box_image'];
        }
        $newData = array_merge($arrayChoose,$arrayNoChoose);    //拼接两个数组
        shuffle($newData); // shuffle()：随机打乱数组，修改的是原数组

        $seriesDetail['stock'] = $stock;
        $seriesDetail['optional'] = $optional;//盲盒盒子可购买数量
        $seriesDetail['totalPrice'] = ($seriesDetail['box_price']) * $optional;//当前页可购买盲盒总价
        $seriesDetail['endPrice'] = ($seriesDetail['box_price']) * 9 - $seriesDetail['reduce_price'];//端盒总价
        //规则
        $aData = M('activity')->getData();
//
        if($aData){
            $seriesDetail['box_rule'] = $aData['rule_setting'];
        }else{
            $seriesDetail['box_rule'] ='暂未设置';
        }

        $this->create_json_info('success', '成功', compact('seriesDetail','newData'));
    }


// 未付款订单
    public function payment(){
        $Params['where'] = ['order_id' =>  I('id')];
//
//        $company = [
//            'pay_date'=>time(),
//            'status' => 2,
//        ];
//        M('order')->edit($company,$Params);
        $OrderInfo = M('order')->getData($Params);
        //吊起支付
        $user_id = $this->getUserId(I('token'));
        $pay = [
            'openid' => $this->getUserOpenid($user_id),
            'money'  => $OrderInfo['pay_price'],
            'order_no' => $OrderInfo['wechat_trade_no'],
        ];
        $jsdk = (new Wechat)->WxPay($pay,'notify_1.php');

        $this->create_json_info('success', '支付成功', compact('jsdk'));
    }

//  唤起支付
    public function getPayment(){
        if(empty(I('typeId'))){
            $this->create_json_info('error', '缺少参数:typeId','','1001');
        }
        if(empty(I('address'))){
            $this->create_json_info('error', '缺少参数:address','','1001');
        }
        if(empty(I('mobile'))){
            $this->create_json_info('error', '缺少参数:mobile','','1001');
        }
        if(empty(I('realname'))){
            $this->create_json_info('error', '缺少参数:realname','','1001');
        }
        if(empty(I('totalPrice'))){
            $this->create_json_info('error', '缺少参数:totalPrice','','1001');
        }


        $user_id = $this->getUserId(I('token'));
        pdo_begin();

        $OrderInfo = [
            'uniacid'=>uniacid(),
            'user_id'=>$user_id,
            'address'=>I('address'),
            'mobile'=>I('mobile'),
            'realname'=>I('realname'),
            'boxTypeId'=>I('typeId'),   //购买的盲盒系统ID
//            'pay_price'=>I('totalPrice'),   //实际支付
            'order_buySum' =>I('totalSum'), //传来的购买数量
            'pay_price'=>0.01,   //实际支付
            'shop_price'=>I('totalPrice'),  //订单金额
            'order_no'=>$this->getOrderNo(),//生成订单号
            'wechat_trade_no'=>$this->getWechatTradeNo(),//微信支付交易单号
            'creation_date' => time(),  //添加时间
            'pay_date'=> time(),    //支付时间
        ];
        //主订单
        if(!$order_id = M('order')->add($OrderInfo)){
            pdo_rollback();
            $this->create_json_info('error', '数据错误','','1001');
        }
        //吊起支付
        $pay = [
            'openid' => $this->getUserOpenid($user_id),
            'money'  => $OrderInfo['pay_price'],
            'order_no' => $OrderInfo['wechat_trade_no'],
        ];
        if(!$jsdk = (new Wechat)->WxPay($pay,'notify_1.php')){
            pdo_rollback();
            $this->create_json_info('error', '数据错误','','1001');
        }
        pdo_commit();
        $this->create_json_info('success', '支付成功', compact('jsdk'));
    }

// 订单列表
    public function OrderLists()
    {
        $user_id = $this->getUserId(I('token'));
        $page = I('page')?I('page'):1;
        $aParams['limit'] = [($page-1)*5,5];
        $aParams['field'] = ['a.*','b.box_img','b.box_name'];
        $aParams['where']['a.user_id'] = $user_id;
        $aParams['join'] = ['leftJoin'=>[
            ['sjtc_manghe_box_series','b','a.boxTypeId','b.id']
        ]];
        if(I('status')== 0 || I('status')==''){
            $aParams['where']['a.status']  < 6;
        }else{
            $aParams['where']['a.status'] = I('status');
        }

        $list = M('order')->lists($aParams);
        foreach ($list as $k=>$v){
            $list[$k]['creation_date'] = date('Y-m-d H:i',$v['creation_date']);
            $list[$k]['boximg'] = tomedia($v['box_img']);
        }
        $this->create_json_info('success', '成功', compact('list'));
    }

// 订单详情
    public function OrderInfo(){
        if(empty(I('order_id'))){
            $this->create_json_info('error', '缺少参数:order_id','','1001');
        }
        $page = I('page')?I('page'):1;
        $aParams['limit'] = [($page-1)*10,10];
        $aParams['field'] = ['a.*','b.box_img','b.box_name'];
        $aParams['where'] = ['a.order_id'=>I('order_id')];
        $aParams['join'] = ['leftJoin'=>[
            ['sjtc_manghe_box_series','b','a.boxTypeId','b.id']
        ]];

        $order = M('order')->getData($aParams);

        $order['boximg'] = tomedia($order['box_img']);
        $order['creation_date'] = date('Y-m-d H:i',$order['creation_date']);
        $order['pay_date'] = date('Y-m-d H:i',$order['pay_date']);
        $order['delivery_date'] = date('Y-m-d H:i',$order['delivery_date']);
        $order['confirm_date'] = date('Y-m-d H:i',$order['confirm_date']);
        $this->create_json_info('success', '成功', compact('order'));
    }

//  确认收货
    public function OrderConfirm(){
        if(empty(I('order_id'))){
            $this->create_json_info('error', '缺少参数:order_id','','1001');
        }
        $aParams['field'] = ['status',];
        $aParams['where'] = ['order_id'=>I('order_id')];
        $order = M('order')->getData($aParams);
        if(!$order) return $this->create_json_info('error', '未找到该订单', '', '1002');

        if($order['status'] != 3) return $this->create_json_info('error', '订单状态有误', '', '1002');
        M('order')->edit(['status'=>4,'confirm_date'=>time()],$aParams);
        $this->create_json_info('success', '收货成功', '');
    }

//  物流信息
    public function wuliu(){
        if(empty(I('order_id'))){
            $this->create_json_info('error', '缺少参数:order_id','','1001');
        }

        $aParams['field'] = ['order_id','status','courier_company','courier_num','courier_no'];
        $aParams['where'] = ['order_id'=>I('order_id')];
        $order = M('order')->getData($aParams);

        $key = 'nCcydWVr3104';						                    //客户授权key
        $customer = '8A9FEF089EFDAA1115E4F68D189F0DBA';					//查询公司编号
        $param = array (
            'com' => $order['courier_num'],		//快递公司编码
            'num' =>  $order['courier_no'],		//快递单号
        );
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/query.do';	//实时查询请求地址
        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";		//默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);

        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result );
        $data = json_decode($data,true);

        $this->create_json_info('success', '成功', compact('data'));
    }
}